const initEle = require('./initEle')()

let globalUtils = require('../utils/compile/index');

module.exports = function (pageDefine, pageName, refs) {
  let _handles = {}

  let _pegeDef = pageDefine.default

  if (!_pegeDef.data) {
    _pegeDef.data = {}
  } else {
    if (globalUtils._.isFunction(_pegeDef.data)) {
      _pegeDef.data = _pegeDef.data()
    }
  }

  _pegeDef.data.__showed = 0

  if (!pageName && page.pageName) {
    pageName = page.pageName
  }
  for (let handleName in _pegeDef.handles) {
    _handles[handleName] = function(e) {
      _pegeDef.handles[handleName].apply(this, [e, e.currentTarget.dataset])
    }
  }

  if (!_pegeDef.onLoad) {
    _pegeDef.onLoad = function () {}
  }

  _pegeDef.onLoad = initEle.initStaticRef(_pegeDef.onLoad, refs, {
    from: 'page',
    fileName: pageName,
    onLoad(context, options = {}) {
      if (wx.hideHomeButton) {
        wx.hideHomeButton()
      }

      let queryString = globalUtils.net.encodeQueryData(options)
      let url = context.route + (queryString ? `?${queryString}` : '')
      context.$pageName = pageName
      context.$mp = {
        query: options,
        queryString: queryString,
        href: url
      }
      context.$globalMessageInstance = context.selectComponent('#globalMessageInstance')
      context.$message = {
        success() {
          context.$globalMessageInstance.show('success')
        },
        error(text) {
          context.$globalMessageInstance.show('error', {
            reason: text
          })
        }
      }

      // console.log('context', context)
    }
  })

  return {
    // onPullDownRefresh() {
    //   const app = getApp()
    //   let self = this
    //    if (app.listenPullDownRefresh) {
    //       app.listenPullDownRefresh(self).then(() => {
    //           if (self.awaitPullDownRefresh) {
    //               self.awaitPullDownRefresh()
    //           }
    //       })
    //    }
    // },
    ..._pegeDef,
    ..._pegeDef.methods,
    ..._handles,
  }
}
